package com.dc.tinymcedemo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/***
 * descriptions...
 * @author Diamon.Cheng
 * @date 2021/7/16
 */
@Controller
public class FileController {
    private static final Logger LOGGER = LoggerFactory.getLogger(FileController.class);
    @Value("${file.save.path:file}")
    private String filePath;
    @Value("${file.mapping.path:/attachment}")
    private String fileMappingPath;
    
    @PostConstruct
    public void init() throws IOException {
        Path dir = FileSystems.getDefault().getPath(filePath);
        LOGGER.info("create dir:{}", dir.toAbsolutePath());
        Files.createDirectories(dir);
    }
    
    /**
     * 上传文件返回地址
     *
     * @param file 文件列表
     * @return AjaxResult
     */
    @PostMapping({"upload","api/upload"})
    @ResponseBody
    public AjaxResult uploadFile(@RequestParam MultipartFile[] file) {
        try {
            List<String> filePaths = new ArrayList<>();
            for (MultipartFile multipartFile : file) {
                String oFileName = multipartFile.getOriginalFilename();
                String suffix = "";
                if (oFileName != null) {
                    int index = oFileName.lastIndexOf('.');
                    if (index != -1) {
                        suffix = oFileName.substring(index);
                    }
                }
                while (true) {
                    String fileSaveName = UUID.randomUUID().toString().substring(28) + suffix;
                    Path fileSavePath = FileSystems.getDefault().getPath(filePath, fileSaveName);
                    if (Files.notExists(fileSavePath)) {
                        Files.copy(multipartFile.getInputStream(), fileSavePath);
                        filePaths.add(fileMappingPath + "/" + fileSaveName);
                        break;
                    }
                }
            }
            return new AjaxResult().setData(filePaths);
        } catch (Exception e) {
            LOGGER.error("", e);
            return new AjaxResult().setSuccess(false).setMessage("上传文件失败 " + e.getMessage());
        }
    }
    
}
